"use client"

import React, { useRef, useEffect, useState, useCallback } from "react"
import { Box, Fab, Tooltip } from "@mui/material"
import { KeyboardArrowDown as ScrollDownIcon } from "@mui/icons-material"
import useAppStore from "@/store/useAppStore"
import ChatMessage from "./ChatMessage"

export default function ConversationPanel() {
	const { messages, isLoading } = useAppStore()
	const scrollRef = useRef<HTMLDivElement>(null)
	const [isUserScrolling, setIsUserScrolling] = useState(false)
	const [showScrollButton, setShowScrollButton] = useState(false)
	const [lastMessageCount, setLastMessageCount] = useState(0)

	// 检查是否在底部附近
	const isNearBottom = useCallback(() => {
		if (!scrollRef.current) return false
		const { scrollTop, scrollHeight, clientHeight } = scrollRef.current
		// 增加底部检测范围，让用户更容易重新启用自动滚动
		return scrollHeight - scrollTop - clientHeight < 150
	}, [])

	// 滚动到底部
	const scrollToBottom = useCallback(() => {
		if (scrollRef.current) {
			scrollRef.current.scrollTo({
				top: scrollRef.current.scrollHeight,
				behavior: "smooth"
			})
		}
		setIsUserScrolling(false)
	}, [])

	// 处理滚动事件
	const handleScroll = useCallback(() => {
		if (!scrollRef.current) return

		const nearBottom = isNearBottom()
		setShowScrollButton(!nearBottom)

		// 如果用户手动滚动离开底部，标记为手动滚动状态
		if (!nearBottom) {
			setIsUserScrolling(true)
		}
	}, [isNearBottom])

	// 智能自动滚动
	useEffect(() => {
		if (!scrollRef.current) return

		// 只有在以下情况才自动滚动：
		// 1. 用户没有手动滚动 且 有新消息
		// 2. 用户滚动到了底部附近（允许重新启用自动滚动）
		const hasNewMessage = messages.length > lastMessageCount
		const isAtBottom = isNearBottom()

		// 如果用户滚动到底部，重新启用自动滚动
		if (isAtBottom && isUserScrolling) {
			setIsUserScrolling(false)
		}

		// 只有在用户没有手动滚动且有新消息时才自动滚动
		const shouldAutoScroll = !isUserScrolling && hasNewMessage

		if (shouldAutoScroll) {
			scrollToBottom()
		}

		setLastMessageCount(messages.length)
	}, [messages, isLoading, isUserScrolling, lastMessageCount, scrollToBottom, isNearBottom])

	// 监听消息内容更新（AI回答时的流式更新）- 使用防抖优化
	useEffect(() => {
		if (!scrollRef.current || !isLoading) return

		// 如果AI正在回答且用户没有手动滚动，自动滚动到最新内容
		if (!isUserScrolling) {
			// 使用requestAnimationFrame优化滚动性能
			requestAnimationFrame(() => {
				scrollToBottom()
			})
		}
	}, [messages, isLoading, isUserScrolling, scrollToBottom])

	return (
		<Box sx={{ position: "relative", flexGrow: 1, overflow: "hidden" }}>
			<Box
				ref={scrollRef}
				onScroll={handleScroll}
				sx={{
					height: "100%",
					overflowY: "auto",
					p: { xs: 2, sm: 3 }, // 增加内边距，给对话更多呼吸空间
					display: "flex",
					flexDirection: "column",
					gap: { xs: 1.5, sm: 2 }, // 减少消息间距，因为每个消息现在有自己的底部间距
					bgcolor: "background.paper", // 使用纯白背景，与外部灰色形成对比
					// 添加渐变背景增强视觉层次
					background: "linear-gradient(180deg, rgba(248, 250, 252, 0.3) 0%, rgba(255, 255, 255, 1) 10%)"
				}}
			>
				{messages.map(msg => (
					<ChatMessage key={msg.id} message={msg} />
				))}
			</Box>

			{/* 滚动到底部按钮 */}
			{showScrollButton && (
				<Tooltip title='滚动到底部'>
					<Fab
						size='small'
						color='primary'
						onClick={scrollToBottom}
						sx={{
							position: "absolute",
							bottom: 16,
							right: 16,
							zIndex: 1000,
							boxShadow: "0 4px 12px rgba(37, 99, 235, 0.3)",
							"&:hover": {
								transform: "scale(1.1)",
								boxShadow: "0 6px 16px rgba(37, 99, 235, 0.4)"
							},
							transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
						}}
					>
						<ScrollDownIcon />
					</Fab>
				</Tooltip>
			)}
		</Box>
	)
}
